import Boss from './Boss.js'
import { CANVAS_WIDTH, CANVAS_HEIGHT } from '../utils/constants.js'

// 高级Boss实现类
export default class AdvancedBoss extends Boss {
  constructor() {
    // 参数：宽度、高度、速度、生命值、分数、类型、图像路径
    super(120, 120, 1.5, 2000, 10000, 'advanced', 'images/boss2.png')

    // 设置Boss名称
    this.name = '虚空统帅'

    // 攻击相关属性
    this.bulletCooldown = 1200 // 子弹冷却时间（毫秒）
    this.lastBulletTime = 0
    this.attackPattern = 'basic' // 当前攻击模式
    this.attackPatterns = [
      'basic',
      'spread',
      'circle',
      'laser',
      'summon',
      'shield',
    ] // 可用攻击模式
    this.attackTimer = 0 // 攻击计时器
    this.attackDuration = 5000 // 每种攻击模式持续时间

    // 特殊攻击相关属性
    this.laserActive = false // 激光攻击是否激活
    this.laserAngle = 0 // 激光角度
    this.laserRotationSpeed = 0.02 // 激光旋转速度
    this.laserWidth = 20 // 激光宽度
    this.laserCharge = 0 // 激光充能
    this.laserChargeTime = 2000 // 激光充能时间

    // 护盾相关属性
    this.hasShield = false // 是否有护盾
    this.shieldHealth = 300 // 护盾生命值
    this.maxShieldHealth = 300 // 最大护盾生命值

    // 召唤相关属性
    this.canSummon = true // 是否可以召唤小敌机
    this.summonCooldown = 8000 // 召唤冷却时间
    this.lastSummonTime = 0 // 上次召唤时间

    // 视觉效果相关属性
    this.chargeEffect = 0 // 充能效果
    this.transitionEffect = 0 // 过渡效果
    this.isTransitioning = false // 是否正在过渡
    this.transitionDuration = 1000 // 过渡持续时间
    this.transitionStartTime = 0 // 过渡开始时间
  }

  // 重写update方法
  update(timestamp) {
    // 调用父类的update方法
    super.update(timestamp)

    // 如果还在入场，不执行攻击
    if (this.isEntering) {
      return
    }

    // 更新攻击计时器
    this.attackTimer += timestamp - (this.lastAttackTimestamp || timestamp)
    this.lastAttackTimestamp = timestamp

    // 如果正在过渡，更新过渡效果
    if (this.isTransitioning) {
      this.updateTransitionEffect(timestamp)
      return
    }

    // 定期切换攻击模式
    if (this.attackTimer >= this.attackDuration) {
      this.attackTimer = 0
      this.changeAttackPattern(timestamp)
    }

    // 根据当前攻击模式执行攻击
    let bullets = []

    switch (this.attackPattern) {
      case 'basic':
      case 'spread':
      case 'circle':
        // 基础子弹攻击
        if (timestamp - this.lastBulletTime > this.bulletCooldown) {
          this.lastBulletTime = timestamp
          bullets = this.fireBullets()
        }
        break
      case 'laser':
        // 激光攻击
        bullets = this.updateLaserAttack(timestamp)
        break
      case 'summon':
        // 召唤小敌机
        if (
          this.canSummon &&
          timestamp - this.lastSummonTime > this.summonCooldown
        ) {
          this.lastSummonTime = timestamp
          bullets = this.summonEnemies()
        }
        break
      case 'shield':
        // 护盾模式
        if (!this.hasShield) {
          this.activateShield()
        }

        // 在护盾模式下也可以发射子弹
        if (timestamp - this.lastBulletTime > this.bulletCooldown * 1.5) {
          this.lastBulletTime = timestamp
          bullets = this.fireBullets()
        }
        break
    }

    return bullets
  }

  // 发射子弹
  fireBullets() {
    const bullets = []

    switch (this.attackPattern) {
      case 'basic':
        // 基础攻击：直线发射多颗子弹
        for (let i = -2; i <= 2; i++) {
          bullets.push({
            x: this.x + this.width / 2 + i * 20,
            y: this.y + this.height,
            speedX: 0,
            speedY: 5,
            damage: 1,
            type: 'normal',
          })
        }
        break
      case 'spread':
        // 扩散攻击：扇形发射子弹
        for (let i = -4; i <= 4; i++) {
          bullets.push({
            x: this.x + this.width / 2,
            y: this.y + this.height,
            speedX: i * 1.5,
            speedY: 5 - Math.abs(i) * 0.5,
            damage: 1,
            type: 'normal',
          })
        }
        break
      case 'circle':
        // 环形攻击：360度发射子弹
        const numBullets = 16
        for (let i = 0; i < numBullets; i++) {
          const angle = (i / numBullets) * Math.PI * 2
          bullets.push({
            x: this.x + this.width / 2,
            y: this.y + this.height / 2,
            speedX: Math.sin(angle) * 4,
            speedY: Math.cos(angle) * 4,
            damage: 1,
            type: 'normal',
          })
        }
        break
      case 'shield':
        // 护盾模式下的攻击：随机散射
        for (let i = 0; i < 3; i++) {
          const angle = Math.random() * Math.PI * 2
          const speed = 3 + Math.random() * 2
          bullets.push({
            x: this.x + this.width / 2,
            y: this.y + this.height / 2,
            speedX: Math.sin(angle) * speed,
            speedY: Math.cos(angle) * speed,
            damage: 1,
            type: 'normal',
          })
        }
        break
    }

    return bullets
  }

  // 更新激光攻击
  updateLaserAttack(timestamp) {
    const bullets = []

    // 如果激光未激活，开始充能
    if (!this.laserActive) {
      this.laserCharge += timestamp - (this.lastLaserTimestamp || timestamp)
      this.lastLaserTimestamp = timestamp

      // 更新充能效果
      this.chargeEffect = this.laserCharge / this.laserChargeTime

      // 充能完成后激活激光
      if (this.laserCharge >= this.laserChargeTime) {
        this.laserActive = true
        this.laserCharge = 0
      }

      return bullets
    }

    // 激光已激活，发射激光
    this.laserAngle += this.laserRotationSpeed
    if (this.laserAngle >= Math.PI * 2) {
      this.laserAngle = 0
    }

    // 创建激光子弹（实际上是一系列沿直线的子弹）
    const laserLength = CANVAS_HEIGHT
    const numSegments = 10
    const segmentLength = laserLength / numSegments

    for (let i = 1; i <= numSegments; i++) {
      const distance = i * segmentLength
      const x = this.x + this.width / 2 + Math.sin(this.laserAngle) * distance
      const y = this.y + this.height / 2 + Math.cos(this.laserAngle) * distance

      bullets.push({
        x: x - this.laserWidth / 2,
        y: y - this.laserWidth / 2,
        speedX: 0,
        speedY: 0,
        damage: 2,
        type: 'laser',
        width: this.laserWidth,
        height: this.laserWidth,
      })
    }

    // 激光持续一段时间后停止
    this.laserCharge += timestamp - (this.lastLaserTimestamp || timestamp)
    this.lastLaserTimestamp = timestamp

    if (this.laserCharge >= this.laserChargeTime * 1.5) {
      this.laserActive = false
      this.laserCharge = 0
      this.chargeEffect = 0
    }

    return bullets
  }

  // 召唤小敌机
  summonEnemies() {
    const enemies = []

    // 在Boss周围召唤3-5个小敌机
    const numEnemies = 3 + Math.floor(Math.random() * 3)

    for (let i = 0; i < numEnemies; i++) {
      const offsetX = (Math.random() - 0.5) * this.width * 2
      const offsetY = (Math.random() - 0.5) * this.height * 2

      enemies.push({
        x: this.x + this.width / 2 + offsetX,
        y: this.y + this.height / 2 + offsetY,
        type: 'summoned',
        health: 2,
        speed: 2 + Math.random(),
      })
    }

    return enemies
  }

  // 激活护盾
  activateShield() {
    this.hasShield = true
    this.shieldHealth = this.maxShieldHealth
  }

  // 护盾受到伤害
  shieldTakeDamage(amount) {
    if (!this.hasShield) return false

    this.shieldHealth -= amount

    // 护盾闪烁效果
    this.isFlashing = true
    this.flashTimer = 0

    // 检查护盾是否被击破
    if (this.shieldHealth <= 0) {
      this.hasShield = false
      return true // 返回true表示护盾被击破
    }

    return false
  }

  // 重写takeDamage方法，添加护盾逻辑
  takeDamage(amount) {
    // 如果有护盾，先对护盾造成伤害
    if (this.hasShield) {
      const isShieldBroken = this.shieldTakeDamage(amount)
      if (!isShieldBroken) {
        return false // 护盾未被击破，Boss不受伤害
      }
      // 护盾被击破，继续处理对Boss的伤害
    }

    // 调用父类的takeDamage方法
    return super.takeDamage(amount)
  }

  // 切换攻击模式
  changeAttackPattern(timestamp) {
    // 保存旧的攻击模式
    const oldPattern = this.attackPattern

    // 根据当前阶段选择可用的攻击模式
    let availablePatterns = []

    switch (this.currentPhase) {
      case 1:
        // 第一阶段只使用基础攻击
        availablePatterns = ['basic', 'spread']
        break
      case 2:
        // 第二阶段添加环形攻击
        availablePatterns = ['basic', 'spread', 'circle']
        break
      case 3:
        // 第三阶段添加激光和召唤
        availablePatterns = ['basic', 'spread', 'circle', 'laser', 'summon']
        break
      case 4:
        // 第四阶段添加护盾
        availablePatterns = [
          'basic',
          'spread',
          'circle',
          'laser',
          'summon',
          'shield',
        ]
        break
    }

    // 随机选择一种攻击模式，但不要连续使用相同的模式
    let newPattern
    do {
      const randomIndex = Math.floor(Math.random() * availablePatterns.length)
      newPattern = availablePatterns[randomIndex]
    } while (newPattern === oldPattern && availablePatterns.length > 1)

    // 开始过渡动画
    this.startTransition(oldPattern, newPattern, timestamp)
  }

  // 开始过渡动画
  startTransition(oldPattern, newPattern, timestamp) {
    this.isTransitioning = true
    this.transitionStartTime = timestamp
    this.oldAttackPattern = oldPattern
    this.newAttackPattern = newPattern
  }

  // 更新过渡效果
  updateTransitionEffect(timestamp) {
    const elapsed = timestamp - this.transitionStartTime
    this.transitionEffect = elapsed / this.transitionDuration

    // 过渡完成
    if (elapsed >= this.transitionDuration) {
      this.isTransitioning = false
      this.transitionEffect = 0
      this.attackPattern = this.newAttackPattern

      // 重置相关状态
      this.laserActive = false
      this.laserCharge = 0
      this.chargeEffect = 0
    }
  }

  // 重写阶段转换方法
  onPhaseTransition(newPhase) {
    // 调用父类的方法
    super.onPhaseTransition(newPhase)

    // 根据新阶段调整属性
    switch (newPhase) {
      case 2:
        this.bulletCooldown = 900 // 第二阶段：加快射速
        this.attackDuration = 4000 // 缩短攻击模式持续时间
        break
      case 3:
        this.bulletCooldown = 800 // 第三阶段：更快射速
        this.attackDuration = 3500 // 更短的攻击模式持续时间
        this.laserRotationSpeed = 0.03 // 加快激光旋转速度
        break
      case 4:
        this.bulletCooldown = 600 // 第四阶段：最快射速
        this.attackDuration = 3000 // 最短的攻击模式持续时间
        this.laserRotationSpeed = 0.04 // 最快激光旋转速度
        this.summonCooldown = 6000 // 缩短召唤冷却时间
        break
    }

    // 切换攻击模式
    this.changeAttackPattern(Date.now())
  }

  // 重写render方法，添加特殊效果
  render(ctx) {
    // 如果正在过渡，绘制过渡效果
    if (this.isTransitioning) {
      this.renderTransitionEffect(ctx)
    }

    // 如果正在充能，绘制充能效果
    if (this.chargeEffect > 0) {
      this.renderChargeEffect(ctx)
    }

    // 调用父类的render方法
    super.render(ctx)

    // 如果有护盾，绘制护盾
    if (this.hasShield) {
      this.renderShield(ctx)
    }

    // 如果激光激活，绘制激光
    if (this.laserActive) {
      this.renderLaser(ctx)
    }
  }

  // 绘制过渡效果
  renderTransitionEffect(ctx) {
    // 绘制一个逐渐扩大的光环
    const radius = this.width * (0.5 + this.transitionEffect)
    const alpha = 1 - this.transitionEffect

    ctx.beginPath()
    ctx.arc(
      this.x + this.width / 2,
      this.y + this.height / 2,
      radius,
      0,
      Math.PI * 2
    )
    ctx.fillStyle = `rgba(255, 255, 255, ${alpha * 0.3})`
    ctx.fill()

    ctx.beginPath()
    ctx.arc(
      this.x + this.width / 2,
      this.y + this.height / 2,
      radius * 0.8,
      0,
      Math.PI * 2
    )
    ctx.strokeStyle = `rgba(255, 255, 255, ${alpha})`
    ctx.lineWidth = 3
    ctx.stroke()
  }

  // 绘制充能效果
  renderChargeEffect(ctx) {
    // 绘制一个逐渐变亮的光环
    const radius = this.width * (0.5 + this.chargeEffect * 0.5)
    const alpha = this.chargeEffect

    ctx.beginPath()
    ctx.arc(
      this.x + this.width / 2,
      this.y + this.height / 2,
      radius,
      0,
      Math.PI * 2
    )
    ctx.fillStyle = `rgba(255, 0, 0, ${alpha * 0.3})`
    ctx.fill()

    ctx.beginPath()
    ctx.arc(
      this.x + this.width / 2,
      this.y + this.height / 2,
      radius * 0.8,
      0,
      Math.PI * 2
    )
    ctx.strokeStyle = `rgba(255, 0, 0, ${alpha})`
    ctx.lineWidth = 3
    ctx.stroke()
  }

  // 绘制护盾
  renderShield(ctx) {
    // 计算护盾健康度百分比
    const healthPercent = this.shieldHealth / this.maxShieldHealth

    // 绘制护盾
    ctx.beginPath()
    ctx.arc(
      this.x + this.width / 2,
      this.y + this.height / 2,
      this.width * 0.6,
      0,
      Math.PI * 2
    )
    ctx.fillStyle = `rgba(0, 100, 255, ${0.2 + healthPercent * 0.3})`
    ctx.fill()

    ctx.beginPath()
    ctx.arc(
      this.x + this.width / 2,
      this.y + this.height / 2,
      this.width * 0.6,
      0,
      Math.PI * 2
    )
    ctx.strokeStyle = `rgba(0, 150, 255, ${healthPercent})`
    ctx.lineWidth = 3
    ctx.stroke()

    // 绘制护盾生命值
    const shieldBarWidth = this.width * 0.8
    const shieldBarHeight = 5
    const shieldBarX = this.x + (this.width - shieldBarWidth) / 2
    const shieldBarY = this.y - 15

    // 背景
    ctx.fillStyle = '#333'
    ctx.fillRect(shieldBarX, shieldBarY, shieldBarWidth, shieldBarHeight)

    // 生命值
    ctx.fillStyle = '#00aaff'
    ctx.fillRect(
      shieldBarX,
      shieldBarY,
      shieldBarWidth * healthPercent,
      shieldBarHeight
    )
  }

  // 绘制激光
  renderLaser(ctx) {
    // 计算激光起点和终点
    const startX = this.x + this.width / 2
    const startY = this.y + this.height / 2
    const length = CANVAS_HEIGHT * 2
    const endX = startX + Math.sin(this.laserAngle) * length
    const endY = startY + Math.cos(this.laserAngle) * length

    // 绘制激光主体
    ctx.beginPath()
    ctx.moveTo(startX, startY)
    ctx.lineTo(endX, endY)
    ctx.strokeStyle = 'rgba(255, 0, 0, 0.8)'
    ctx.lineWidth = this.laserWidth
    ctx.stroke()

    // 绘制激光内核
    ctx.beginPath()
    ctx.moveTo(startX, startY)
    ctx.lineTo(endX, endY)
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.9)'
    ctx.lineWidth = this.laserWidth / 3
    ctx.stroke()

    // 绘制激光起点光晕
    ctx.beginPath()
    ctx.arc(startX, startY, this.laserWidth, 0, Math.PI * 2)
    ctx.fillStyle = 'rgba(255, 0, 0, 0.8)'
    ctx.fill()

    ctx.beginPath()
    ctx.arc(startX, startY, this.laserWidth / 2, 0, Math.PI * 2)
    ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
    ctx.fill()
  }
}
